package v1

import (
	"auth/bll"
	"auth/model"
	"auth/server/web/middleware"
	"auth/utils"
	"github.com/gin-gonic/gin"
)

var Api = &api{}

type api struct{}

func (a *api) Init(r *gin.RouterGroup) {
	g := r.Group("/api", middleware.Auth())
	{
		g.POST("/create", a.create)
		g.POST("/update", a.update)
		g.POST("/list", a.list)
		g.POST("/delete", a.delete)
		g.POST("getAllApis", a.getAllApis) // 获取所有api
	}
}

func (a *api) create(c *gin.Context) {
	var (
		in  = &model.ApiCreateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.Api.Create(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOK(c, nil)
}

func (a *api) update(c *gin.Context) {
	var (
		in  = &model.ApiUpdateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.Api.Update(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOK(c, nil)
}

func (a *api) list(c *gin.Context) {
	var (
		in  = &model.ApiListRequest{}
		out = &model.ApiListResponse{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.Api.List(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOK(c, out)
}

func (a *api) delete(c *gin.Context) {
	var (
		in  = &model.ApiDeleteRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.Api.Delete(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOK(c, nil)
}

func (a *api) getAllApis(c *gin.Context) {
	var (
		err error
		out = &model.GetAllApisResponse{}
	)
	if out, err = bll.Api.GetAllApis(c.Request.Context()); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOK(c, out)
}
